package com.android.videotest.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.android.videotest.R;
import com.android.videotest.video.VideoActivity;

import java.io.File;

public class FilesActivity extends AppCompatActivity {

    private FilesActivity mFilesActivity;
    private File currentFile;
    private File[] files;
    ListView listView;
    private String rootPath = Environment.getExternalStorageDirectory().getPath();

    public static void start(Context context) {
        Intent starter = new Intent(context, FilesActivity.class);
//    starter.putExtra();
        context.startActivity(starter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_files);
        mFilesActivity = this;
        listView = findViewById(R.id.listView);

        File rootDir = new File(Environment.getExternalStorageDirectory().getPath());
        files = rootDir.listFiles();
        listView.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, files));
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                currentFile = files[position];
                if (currentFile.isFile()) {
                    if (currentFile.getName().endsWith(".mp4")) {
                        VideoActivity.start(mFilesActivity, currentFile.getPath());
                    } else {
//                        Uri uri = Uri.parse(currentFile.getAbsolutePath());
//                        Intent intent = new Intent(Intent.ACTION_VIEW);
//                        intent.setData(uri);
//                        startActivity(intent);
                    }
                } else {
                    files = currentFile.listFiles();
                    if (files != null) {
                        listView.setAdapter(new ArrayAdapter<>(mFilesActivity, android.R.layout.simple_list_item_1, files));
                    }
                }
            }
        });
    }

    @Override
    public void onBackPressed() {
        if (currentFile == null) {
            super.onBackPressed();
            return;
        }
        if (!currentFile.getPath().equals(rootPath)) {
            currentFile = currentFile.getParentFile();
            files = currentFile.listFiles();
            listView.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, files));
        } else {
            super.onBackPressed();
        }
    }
}
